<?php

namespace App\Models\MainDB\Task;

use App\Enums\TaskEnum;
use Illuminate\Database\Eloquent\Model;

class TaskUser extends Model{

    protected $table = 'ln_task_user';

    protected $primaryKey = 'id';

    protected $appends = ['extra_data'];

    protected $fillable = [
        "id",
        "name",
        "desc",
        "unique_id",
        "user_id",
        "module_id",
        "type_id",
        "task_config_id",
        "reward_id",
        "expire_time",
        "task_degree",
        "target_limit",
        "parent_unique_id",
        "extra_json",
        "add_time",
        "update_time",
        "is_deleted",
        'reward_number',
        'reward_type',
        "status",
    ];

    public $timestamps = false;

    // 更新任务进度
    public function updateDegree($aftDegree) {
        if ($this->getAttribute("status") == TaskEnum::TASK_USER_HAS_GET) {
            return false;
        }
        $targetLimit = $this->getAttribute("target_limit");

        $this->setAttribute("update_time", time());

        $preTaskDegree = $this->getAttribute("task_degree");

        if (
            $preTaskDegree < $targetLimit &&
            $aftDegree >= $targetLimit
        ) {
            // 从未完成到已完成
            $this->setAttribute('task_degree', $targetLimit);
            $this->setAttribute('status', TaskEnum::TASK_USER_HAS_FINISH);
        } elseif (
            $preTaskDegree == $targetLimit &&
            $aftDegree < $targetLimit
        ) {
            // 从已完成到未完成
            $this->setAttribute('task_degree', $aftDegree);
            $this->setAttribute('status', TaskEnum::TASK_USER_UN_FINISH);
        } elseif (
            // 从已完成到已完成
            $preTaskDegree == $targetLimit &&
            $aftDegree >= $targetLimit
        ) {
            $this->setAttribute('task_degree', $targetLimit);
        } else {
            // 从未完成到未完成
            $this->setAttribute('task_degree', $aftDegree);
        }

        return $this->save();
    }

    public function getExtraDataAttribute()
    {
        $extraJson = $this->getAttribute("extra_json");
        if (!$extraJson) {
            return [];
        }

        $extraData = json_decode($extraJson, 1);
        if (json_last_error()) {
            return [];
        }

        return $extraData;
    }

    public function reward() {
        return $this->hasOne('App\Models\MainDB\Reward', 'id', 'reward_id');
    }

    public function task_type() {
        return $this->hasOne('App\Models\MainDB\Task\TaskType', 'id', 'type_id');
    }

    public function reward_detail() {
        return $this->hasManyThrough('App\Models\MainDB\RewardDetail', 'App\Models\MainDB\Reward', "id", "reward_id", "reward_id", "id");
    }

}